from typing import List
from fastapi import FastAPI, Form, WebSocket, WebSocketDisconnect
import json
from catchObj.Stocks import Stocks
from pydantic import BaseModel
from server import algorithm,pdStocks
import func
import numpy as np

app = FastAPI()

class Item(BaseModel):
    action: str
    code:str


@app.post("/py")
async def py(item:Item):
    daily = pdStocks.PdStocks.getDaily(item.code)
    tt=[]
    if item.action == 'kdj':
        algorithm.KDJ(daily)
        tt = func.to_json2(daily[['date','k','d','j']])
    elif item.action == 'boll':
        algorithm.BOLL(daily)
        tt = func.to_json2(daily[['date','median','lower','upper']])
    elif item.action == 'rsi':
        algorithm.RSI(daily)
        tt=func.to_json2(daily[['close','date','rsi_6']])
        
    return tt['data']

@app.post("/daily")
async def daily(item:Item):
    print(item.code)
    daily = Stocks.getDaily(item.code)
    return daily


@app.get("/allstock")
async def allstock():
    stocks = Stocks.getAllStocks()
    return stocks


@app.websocket("/test/{user}")
async def websocket_endpoint(websocket: WebSocket, user: str):
    await websocket.accept()

    try:
        while True:
            data = await websocket.receive_json()
            print('recive data:',data['action'])
            if data['action']=="ping":
                await websocket.send_json({'action':"pong"})
            elif data['action'] == 'analyse':
                await websocket.send_json({'action':"analyse"})
            else:
                await websocket.send_json({'action':'pingceshi'})

    except WebSocketDisconnect:
        print("client close")
        # await websocket.send_json({'action':"close"})
        websocket.close()

if __name__ == "__main__":
    import uvicorn
    # 官方推荐是用命令后启动 uvicorn main:app --host=127.0.0.1 --port=8010 --reload
    uvicorn.run(app='main:app', host="127.0.0.1", port=5000, reload=True, debug=True)